/**
 * 后端请求方法 依赖 jQuery layer
 */
import layer from "./layer.js"

var request = new function(){
	this.post = async function(url ,data){
			return fetch(url,{
					method: 'POST',
					headers:{
						"token":sessionStorage.getItem('token'),
						'Accept': 'application/json, text/plain, */*',
                    	'Content-Type': 'application/json'
					},
					body:JSON.stringify(data)
				}).then(response=>{
					if(response.status == 200){
						return response.json();
					}
					return Promise.reject(response)
				}).catch(err=>{
					return Promise.reject(err)
				}).then(res=>{
					if(res.code > 0){
						switch(res.code){
							case 3:
							case 4:sessionStorage.clear();
										window.location.href ="/login.html";
						}
						return Promise.reject(res)
					}else{
						return res
					}
				})
			
		}
		
		this.postAlert =async function(url ,data){
			var _this = this;
			return fetch(url,{
					method: 'POST',
					headers:{
						"token":sessionStorage.getItem('token'),
						'Content-Type': 'application/json;charset=UTF-8' ,
						"Accept":"application/json, text/plain, */*",
					},
					body:JSON.stringify(data)
				}).then(response=>{
					if(response.status == 200){
						return response.json();
					}
					return Promise.reject(response)
				}).catch((err)=>{
					_this.alert("服务器繁忙,请稍后再试~",danger);
					
					return Promise.reject(err)
				}).then(res=>{
					if(res.code > 0){
						layer.alert(res.msg,"warning")
						switch(res.code){
							case 3:
							case 4:sessionStorage.clear();
										window.location.href ="/login.html";
						}
						return Promise.reject(res)
					}else if(res.code == 0){
						layer.alert(res.msg);
						return res
					}
				})
		}
}
export default request;